import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Row,
  Col,
  Button,
  Tabs,
  Form,
  Input,
  Select,
  Switch,
  Space,
  Divider,
  message,
  Tag,
  Alert,
} from 'antd';
import { EditOutlined, DeleteOutlined, ArrowLeftOutlined, SaveOutlined, EyeOutlined, HistoryOutlined } from '@ant-design/icons';
import { getApiDetail, updateApi, deleteApi } from '../../../services/api';

const { Option } = Select;
const { TabPane } = Tabs;

const ApiDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [apiData, setApiData] = useState(null);
  const [editing, setEditing] = useState(false);
  const [form] = Form.useForm();
  const [historyData, setHistoryData] = useState([]);

  // Fetch API detail
  const fetchApiDetail = async () => {
    setLoading(true);
    try {
      const res = await getApiDetail(id);
      if (res.success) {
        setApiData(res.data);
        form.setFieldsValue({
          name: res.data.name,
          description: res.data.description,
          url: res.data.url,
          method: res.data.method,
          status: res.data.status,
          timeout: res.data.timeout,
          ratelimit: res.data.ratelimit,
          authRequired: res.data.authRequired,
          requestHeaders: JSON.stringify(res.data.requestHeaders || {}, null, 2),
          requestBody: JSON.stringify(res.data.requestBody || {}, null, 2),
          responseExample: JSON.stringify(res.data.responseExample || {}, null, 2),
        });
      }
    } catch (error) {
      console.error('Failed to fetch API detail:', error);
      message.error('获取API详情失败');
    } finally {
      setLoading(false);
    }
  };

  // Fetch API history
  const fetchApiHistory = async () => {
    try {
      // 这里应该调用获取API历史的接口
      // 目前使用模拟数据
      const mockHistory = [
        {
          id: 1,
          version: 'v1.2.0',
          updatedBy: 'admin',
          updatedAt: '2024-10-08 15:30:00',
          changes: ['更新了请求参数', '优化了响应格式'],
        },
        {
          id: 2,
          version: 'v1.1.0',
          updatedBy: 'admin',
          updatedAt: '2024-10-01 10:15:00',
          changes: ['添加了认证要求', '增加了超时设置'],
        },
        {
          id: 3,
          version: 'v1.0.0',
          updatedBy: 'admin',
          updatedAt: '2024-09-15 09:00:00',
          changes: ['创建API'],
        },
      ];
      setHistoryData(mockHistory);
    } catch (error) {
      console.error('Failed to fetch API history:', error);
    }
  };

  // Initial data fetch
  useEffect(() => {
    if (id) {
      fetchApiDetail();
      fetchApiHistory();
    }
  }, [id]);

  // Handle edit toggle
  const handleEditToggle = () => {
    if (editing) {
      // If canceling edit, reset form with original data
      form.setFieldsValue({
        name: apiData.name,
        description: apiData.description,
        url: apiData.url,
        method: apiData.method,
        status: apiData.status,
        timeout: apiData.timeout,
        ratelimit: apiData.ratelimit,
        authRequired: apiData.authRequired,
        requestHeaders: JSON.stringify(apiData.requestHeaders || {}, null, 2),
        requestBody: JSON.stringify(apiData.requestBody || {}, null, 2),
        responseExample: JSON.stringify(apiData.responseExample || {}, null, 2),
      });
    }
    setEditing(!editing);
  };

  // Handle save
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 处理JSON字段
      const formattedValues = {
        ...values,
        requestHeaders: values.requestHeaders ? JSON.parse(values.requestHeaders) : {},
        requestBody: values.requestBody ? JSON.parse(values.requestBody) : {},
        responseExample: values.responseExample ? JSON.parse(values.responseExample) : {},
      };

      const res = await updateApi(id, formattedValues);
      if (res.success) {
        message.success('API更新成功');
        setApiData(res.data);
        setEditing(false);
      }
    } catch (error) {
      console.error('Failed to update API:', error);
      message.error('API更新失败');
    } finally {
      setLoading(false);
    }
  };

  // Handle delete
  const handleDelete = async () => {
    try {
      const res = await deleteApi(id);
      if (res.success) {
        message.success('API删除成功');
        navigate('/api');
      }
    } catch (error) {
      console.error('Failed to delete API:', error);
      message.error('API删除失败');
    }
  };

  // Handle back
  const handleBack = () => {
    navigate('/api');
  };

  if (loading && !apiData) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '50vh' }}>
        <Alert message="加载中..." type="info" />
      </div>
    );
  }

  if (!apiData) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '50vh' }}>
        <Alert message="API不存在或已被删除" type="error" />
      </div>
    );
  }

  return (
    <div className="api-detail">
      {/* Header with Actions */}
      <div className="detail-header">
        <Space>
          <Button icon={<ArrowLeftOutlined />} onClick={handleBack}>返回列表</Button>
          {editing ? (
            <>
              <Button type="primary" icon={<SaveOutlined />} onClick={handleSave} loading={loading}>保存</Button>
              <Button onClick={handleEditToggle}>取消</Button>
            </>
          ) : (
            <>
              <Button type="primary" icon={<EditOutlined />} onClick={handleEditToggle}>编辑</Button>
              <Button danger icon={<DeleteOutlined />} onClick={handleDelete}>删除</Button>
            </>
          )}
        </Space>
      </div>

      <Divider />

      {/* API Info */}
      <Card title="API基本信息" className="mb-4">
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={8}>
            <div className="info-item">
              <span className="info-label">API ID:</span>
              <span className="info-value">{apiData.id}</span>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <div className="info-item">
              <span className="info-label">创建时间:</span>
              <span className="info-value">{apiData.createdAt}</span>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <div className="info-item">
              <span className="info-label">更新时间:</span>
              <span className="info-value">{apiData.updatedAt}</span>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <div className="info-item">
              <span className="info-label">创建人:</span>
              <span className="info-value">{apiData.createdBy}</span>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <div className="info-item">
              <span className="info-label">更新人:</span>
              <span className="info-value">{apiData.updatedBy}</span>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <div className="info-item">
              <span className="info-label">状态:</span>
              <Tag color={apiData.status === 'active' ? 'green' : 'gray'}>
                {apiData.status === 'active' ? '启用' : '禁用'}
              </Tag>
            </div>
          </Col>
        </Row>
      </Card>

      {/* API Configuration */}
      <Tabs defaultActiveKey="1" className="mb-4">
        <TabPane tab="配置详情" key="1">
          <Form
            form={form}
            layout="vertical"
            disabled={!editing}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} md={12}>
                <Form.Item
                  name="name"
                  label="API名称"
                  rules={[{ required: true, message: '请输入API名称' }]}
                >
                  <Input placeholder="请输入API名称" />
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="description"
                  label="API描述"
                >
                  <Input.TextArea placeholder="请输入API描述" rows={2} />
                </Form.Item>
              </Col>
              <Col xs={24} md={8}>
                <Form.Item
                  name="method"
                  label="请求方法"
                  rules={[{ required: true, message: '请选择请求方法' }]}
                >
                  <Select placeholder="请选择请求方法">
                    <Option value="GET">GET</Option>
                    <Option value="POST">POST</Option>
                    <Option value="PUT">PUT</Option>
                    <Option value="DELETE">DELETE</Option>
                    <Option value="PATCH">PATCH</Option>
                    <Option value="HEAD">HEAD</Option>
                    <Option value="OPTIONS">OPTIONS</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col xs={24} md={16}>
                <Form.Item
                  name="url"
                  label="请求URL"
                  rules={[{ required: true, message: '请输入请求URL' }]}
                >
                  <Input placeholder="请输入请求URL" />
                </Form.Item>
              </Col>
              <Col xs={24} md={8}>
                <Form.Item
                  name="timeout"
                  label="超时时间(ms)"
                  rules={[{ required: true, message: '请输入超时时间' }]}
                >
                  <Input type="number" placeholder="请输入超时时间" />
                </Form.Item>
              </Col>
              <Col xs={24} md={8}>
                <Form.Item
                  name="ratelimit"
                  label="请求限制(QPS)"
                  rules={[{ required: true, message: '请输入请求限制' }]}
                >
                  <Input type="number" placeholder="请输入请求限制" />
                </Form.Item>
              </Col>
              <Col xs={24} md={8}>
                <Form.Item
                  name="status"
                  label="状态"
                  rules={[{ required: true, message: '请选择状态' }]}
                >
                  <Select placeholder="请选择状态">
                    <Option value="active">启用</Option>
                    <Option value="inactive">禁用</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col xs={24} md={8}>
                <Form.Item
                  name="authRequired"
                  label="需要认证"
                  valuePropName="checked"
                >
                  <Switch />
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item
                  name="requestHeaders"
                  label="请求头"
                  tooltip="JSON格式，例如：{'Content-Type': 'application/json'}"
                >
                  <Input.TextArea placeholder="请输入请求头(JSON格式)" rows={4} />
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item
                  name="requestBody"
                  label="请求体"
                  tooltip="JSON格式，例如：{'name': 'test'}"
                >
                  <Input.TextArea placeholder="请输入请求体(JSON格式)" rows={6} />
                </Form.Item>
              </Col>
              <Col xs={24}>
                <Form.Item
                  name="responseExample"
                  label="响应示例"
                  tooltip="JSON格式，例如：{'code': 200, 'data': {}}"
                >
                  <Input.TextArea placeholder="请输入响应示例(JSON格式)" rows={6} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </TabPane>

        <TabPane tab="历史版本" key="2">
          <div className="history-list">
            {historyData.map((item) => (
              <Card key={item.id} title={`版本：${item.version} (${item.updatedAt})`} className="mb-4">
                <div className="history-info">
                  <p><strong>更新人：</strong>{item.updatedBy}</p>
                  <p><strong>更新内容：</strong></p>
                  <ul>
                    {item.changes.map((change, index) => (
                      <li key={index}>{change}</li>
                    ))}
                  </ul>
                </div>
                <Button type="link" icon={<EyeOutlined />}>查看详情</Button>
              </Card>
            ))}
          </div>
        </TabPane>

        <TabPane tab="使用统计" key="3">
          <Card className="mb-4">
            <p>API调用次数：10,245</p>
            <p>平均响应时间：120ms</p>
            <p>成功率：99.8%</p>
            <Button type="primary" icon={<HistoryOutlined />}>查看详细统计</Button>
          </Card>
        </TabPane>
      </Tabs>

      {/* API Documentation */}
      <Card title="API文档" className="mb-4">
        <div className="api-docs">
          <p>这里是API的详细文档内容，包括：</p>
          <ul>
            <li>API的功能说明</li>
            <li>请求参数说明</li>
            <li>响应格式说明</li>
            <li>错误码说明</li>
            <li>使用示例</li>
          </ul>
          <Button type="link">查看完整文档</Button>
        </div>
      </Card>
    </div>
  );
};

export default ApiDetail;